#! /usr/bin/env python
#coding:utf-8
import os
import smtplib
import sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
#定义函数 _sendmail
def _sendmail(smtp_server,port,account,password,str_from,list_to,msg):
    smtp = smtplib.SMTP(smtp_server,port)
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
#    smtp.login(account, password)
    smtp.sendmail(str_from, list_to,msg)
    smtp.close()
        
# 定义函数 _get_pictures
#def _get_pictures(image_dir):
#建立空列表Pictures
#    pictures = []
#os.listdir 返回指定目录下的所有文件和目录名
#    for f in os.listdir(image_dir):
# append 是在列表最后增加内容，这里是将list出来的信息f增加到Picture列表中
#        pictures.append(f)
#    return pictures
# 定义函数 _create_msg
def _create_msg(screen_name,screens,image_dir,str_from,list_to):
    msgRoot = MIMEMultipart('related')
        
# 定义邮件主题
    msgRoot['Subject'] = 'Zabbix Report: %s' % screen_name
        
#定义发件人、收件人
    msgRoot['From'] = str_from
    msgRoot['To'] = ",".join(list_to)
    msgRoot.preamble = 'This is a multi-part message in MIME format.'
    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)
# 定义邮件正文内容
    msgText = MIMEText('This is the alternative plain text message.')
    msgAlternative.attach(msgText)
    contents = ""
    contents += "<h3>索能达IT运维平台 %s</h3><br>" % image_name
        
    contents +="<table>"
        
# 定义邮件中的图片文件名：image_name
    image_id = '%s' % sys.argv[1]

    fp = open("%s" % (image_fullpath),'rb')
    msgImage = MIMEImage(fp.read())
            
    fp.close()
            
    msgImage.add_header('Content-ID', "<%s>" % image_name)
    msgRoot.attach(msgImage)
    contents +="<td><img src='cid:%s'></td>" % image_name
            
# table结束   
    contents += "</table>"
# 定义邮件格式为HTML
    msgText = MIMEText(contents, 'html')
        
    msgAlternative.attach(msgText)
#    msgRoot.attach(msgAlternative)
    return msgRoot
# Create the root message and fill in the from, to, and subject headers
def main(str_from,list_to,image_dir):
#    pictures = _get_pictures(image_dir)
    screen = "screen999999999999999999999999999"
    msgRoot = _create_msg(image_name,screen,image_dir,str_from,list_to)
            
#定义邮件服务器地址、端口
    _sendmail(smtp_server,port,'','',str_from,list_to,msgRoot.as_string())
# 定义发送邮件信息，发件人，收件人，图片目录
if __name__ == '__main__':
   smtp_server = '10.210.1.227'
   port = 25
   str_from = 'adm_zbx@sonepar.com.cn'
   list_to = [
                "roger.ling@sonepar.com.cn"
             ]
   item_id = sys.argv[1]
   image_name =  "itemid-%s.png" % item_id
   image_dir = "/data/graph/trigger-%s" % item_id
   image_fullpath = "%s/%s" % (image_dir,image_name)
   main(str_from,list_to,image_dir)




